const util = require("../../utils/util");
const {
  handleToast,
  handleAlert,
  closeToast
} = require("../../utils/alertUtil");
const {
  initBluetooth,
  getBluetoothState,
  startSearchDevice,
  connectDevice,
  disconnectDevice,
  stopSearchDevice,
  deinitBluetooth,
  queryDeviceBasicInfo
} = requirePlugin("hello-plugin")
const globalData_ = requirePlugin("hello-plugin")
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    BluetoothDataList: [],
    devices: [],
    connected: false,
    chs: [],
    isConnectedBluetooth: false,
    BDevName: "",
    deviceId: "",
    showModal: false,
  },
  // mark : 页面下拉刷新事件
  onPullDownRefresh(){
    wx.showLoading({
      title: '正在刷新...',
  });
  const that = this;
  //  this.onLoad()
   startSearchDevice(
    function (res) {
      that.setData({
        devices: res
      })
    }
  );
  setTimeout(()=>{
    stopSearchDevice()
  },6000)

    setTimeout(() => {
      wx.hideLoading(); // 隐藏刷新提示框
      wx.showToast({
          title: '刷新成功',
          icon: 'success',
      });
      wx.stopPullDownRefresh(); // 停止下拉刷新
  }, 2000);
  },
  onLoad() {
    var that = this
    app.globalData.isSearch = true
    // this.closeBluetoothAdapter();
    // 1.初始化蓝牙
    if (!app.globalData.isConnectedBluetooth) {
      // deinitBluetooth()
      const deviceId = wx.getStorageSync('deviceId') || app.globalData.deviceId
      if (deviceId) {
        this.closeBLEConnection()
      }
      setTimeout(()=>{
        initBluetooth(function (res) {
          if (res == "success") {
            // 3.开始搜索蓝牙设备
            startSearchDevice(
              function (res) {
                that.setData({
                  devices: res
                })
              }
            );
            setTimeout(()=>{
              stopSearchDevice()
            },6000)

          }
        });
      },1000)

    }

    // 2.获取蓝牙状态
    // getBluetoothState();'


    // 4.获取搜索到的蓝牙设备数据
    // deviceFound();
    this.setData({
      isConnectedBluetooth: app.globalData.isConnectedBluetooth,
      BDevName: app.globalData.BDevName,
      deviceId: app.globalData.deviceId
    })
  },
  onShow() {
    const deviceId = wx.getStorageSync('deviceId') || app.globalData.deviceId
    const deviceName = wx.getStorageSync('deviceName') || app.globalData.BDevName
    this.setData({
      deviceId: deviceId,
      BDevName: deviceName
    })
  },
  // 点击连接
  stopScanBle() {
    var that = this;
    that.stopBluetoothDevicesDiscovery();
    that.closeBluetoothAdapterShow();
    util.printLog("停止搜索")
    // that.closeBluetoothAdapter();
  },

  // 监听蓝牙得状态
  getBluetoothAdapterState() {
    util.printLog("------------------ 监听蓝牙状态")
    wx.getBluetoothAdapterState({
      success: (res) => {
        util.printLog('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  //搜索设备
  startBluetoothDevicesDiscovery() {
    util.printLog("------------------03 搜索蓝牙设备 serviceId" + this.data.serviceId)
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      services: "",
      allowDuplicatesKey: true,
      success: (res) => {
        util.printLog('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },

  // // 获取所有已发现的设备
  onBluetoothDeviceFound() {
    util.printLog("------------------04 获取蓝牙设备")
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        // util.printLog("=====获取蓝牙设备  "+ JSON.stringify(res));
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)

      })
      const devs = ListSortAsc(this.data.devices);
      this.setData({
        devices: devs
      });
      // util.printLog(JSON.stringify(ListSortAsc(this.data.devices)));
    })

  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  // mark: 连接设备
  createBLEConnection(e) {
    stopSearchDevice();
    var that = this
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    this.setData({
      showModal: true,
    })

    util.printLog("------------点击连接" + deviceId  + ", " + JSON.stringify(e))
    setTimeout(
      () => {
        // 连接设备
        connectDevice(deviceId, function (isTrue, res) {
          util.printLog(" 连接蓝牙回调：" + isTrue, res)
          if (isTrue) {
            wx.setStorageSync('deviceId', deviceId)
            wx.setStorageSync('deviceName', name)
            queryDeviceBasicInfo((state, res) =>{
              console.log("设备类型：",res.deviceType);
              app.globalData.deviceInfo = res
              that.setData({
                connected: true,
                BDevName: name,
                deviceId: deviceId,
                showModal: false
              })
              app.globalData.deviceId = deviceId
              app.globalData.BDevName = name
              app.globalData.isConnectedBluetooth = true;
              closeToast();
              wx.reLaunch({
                url: '/pages/index/index',
              })
              handleToast("连接" + name + "成功！", "success", 2)
            })
          } else {
            handleToast("连接" + name + "失败！" + res, "error", 3.5)
          }
        })
      },
      500
    )

    // this.stopBluetoothDevicesDiscovery()
  },
  // 
  closeBLEConnection() {

    let that = this;
    util.printLog("================开始断开连接：" + that.data.BDevName)

    disconnectDevice(that.data.deviceId, function (isTrue, res) {
      wx.setStorageSync('deviceId', null)
      util.printLog(" 断开连接：" + isTrue, res)
      if (isTrue) {
        util.printLog("================断开连接成功：" + that.data.BDevName + "---res", res)
        app.globalData.isConnectedBluetooth = false;
        app.globalData.BDevName = "";
        globalData_.resetConnectGloablData();
        wx.reLaunch({
          url: '/pages/index/index',
        })
      } else {
        util.printLog("================断开连接时发生错误：", res)
      }
    })

    
    // wx.closeBLEConnection({
    //   deviceId: that.data.deviceId,
    //   success(res) {
    //     util.printLog("================断开连接成功：" + that.data.BDevName + "---res", res)
    //     app.globalData.isConnectedBluetooth = false;
    //     app.globalData.BDevName = "";
    //     globalData_.resetConnectGloablData();
    //     wx.reLaunch({
    //       url: '/pages/index/index',
    //     })
    //   },
    //   fail(res) {
    //     util.printLog("================断开连接时发生错误：", res)
    //   }
    // })
    that.setData({
      isConnectedBluetooth: false,
      chs: [],
      name: "",
    })
  },
  onUnload() {
    app.globalData.isSearch = false
  }


})